<!-- WordQuiz.vue -->
<template>
  <div class="word-quiz">
    <h3>单词选择题（共 {{ count }} 题）</h3>

    <div v-for="q in questions" :key="q.id" class="question" :id="q.id">
      <div class="question-text">
        <strong>{{ questions.indexOf(q) + 1 }}.</strong>
        <span class="word">{{ q.word }}</span>
      </div>

      <!-- 选项单行显示 -->
      <div class="options">
        <button
            v-for="(opt, idx) in q.options"
            :key="idx"
            class="option"
            :class="{
            selected: userAnswers[q.id] === opt,
            correct: showResult && opt === q.correct,
            wrong: showResult && userAnswers[q.id] === opt && opt !== q.correct
          }"
            @click="selectOption(q.id, opt)"
            :disabled="showResult"
        >
          {{ String.fromCharCode(65 + idx) }}. {{ opt }}
        </button>
      </div>
    </div>

    <div class="actions">
      <button v-if="!showResult" @click="submit" class="btn-submit">
        提交答案
      </button>
    </div>

    <!-- 结果显示 -->
    <div v-if="showResult" class="result">
      <h4>
        答对 {{ questions.filter(q => userAnswers[q.id] === q.correct).length }} / {{ count }}
        题
      </h4>
      <p :style="{ color: accuracy >= 80 ? '#52c41a' : accuracy >= 60 ? '#faad14' : '#f5222d' }">
        正确率：{{ correctRate }}%
      </p>
    </div>
  </div>
</template>
<script setup>
import { ref, computed } from 'vue'
import {shuffleArray} from "@/api/utils/index.js";

onMounted(() => {
  // 组件加载时初始化题目
  initQuestions()
})

// 定义 props
const props = defineProps({
  // 单词库：{ "apple": "苹果", ... }
  words: {
    type: Object,
    required: true
  },
  // 题目数量
  count: {
    type: Number,
    default: 30
  }
})

// 定义 emit 事件
const emit = defineEmits(['finish'])

// 所有中文意思（用于生成干扰项）
const chineseWords = computed(() => Object.values(props.words))

// 生成题目
const questions = ref([])
const userAnswers = ref({}) // 用户选择 { q0: '苹果', ... }
const showResult = ref(false)

let practiceId = ref(null)
const correctRate = ref('')

// 打乱数组
const shuffle = (arr) => {
  const a = [...arr]
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[a[i], a[j]] = [a[j], a[i]]
  }
  return a
}

// 生成干扰项（3个错误选项）
const generateDistractors = (correct, all) => {
  return shuffle(all.filter(w => w !== correct)).slice(0, 3)
}

// 初始化题目
const initQuestions = () => {
  let words = props.words;
  // console.log(words)
  if (words === undefined || words === null) {
    return
  }
  const wordList = Object.keys(props.words)
  const list = []

  for (let i = 0; i < props.count; i++) {
    const word = wordList[i]
    const correct = props.words[word]
    const distractors = generateDistractors(correct, chineseWords.value)
    const options = shuffle([correct, ...distractors])

    list.push({
      id: `q${i}`,
      word,
      options,
      correct
    })
  }

  questions.value = shuffleArray(list)
  userAnswers.value = {}
  practiceId.value = Math.random().toString().substring(2)
  showResult.value = false
}

// 选择选项
const selectOption = (qid, option) => {
  userAnswers.value[qid] = option
}

// 提交测试
const submit = () => {
  let correctCount = 0
  questions.value.forEach(q => {
    q['selected'] = userAnswers.value[q.id]
    q['practiceId'] = practiceId.value
    if (userAnswers.value[q.id] === q.correct) correctCount++
  })

  const accuracy = (correctCount / props.count) * 100
  correctRate.value = accuracy.toFixed(1)

  // 触发完成事件
  emit('finish', {
    correct: correctCount,
    total: props.count,
    accuracy: accuracy.toFixed(1)
  })

  showResult.value = true
}


</script>

<style scoped>
.word-quiz {
  font-family: 'Microsoft YaHei', sans-serif;
  max-width: 1200px;
  margin: 0 auto;
  background: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h3 {
  text-align: center;
  color: #1890ff;
  margin-bottom: 20px;
}

.question {
  margin: 18px 0;
  padding: 14px;
  background: #f9f9f9;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.question-text {
  font-size: 15px;
  margin-bottom: 10px;
  color: #333;
}

.word {
  color: #1890ff;
  font-size: 20px;
  font-weight: bold;
}

.options {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.option {
  flex: 1;
  padding: 8px 12px;
  background: #f0f8ff;
  border: 1px solid #91d5ff;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.option:hover:not(.selected):not(:disabled) {
  background: #91d5ff;
  color: white;
}

.option.selected {
  background: #1890ff;
  color: white;
  border-color: #1890ff;
}

.option.correct {
  background: #52c41a;
  color: white;
  border-color: #52c41a;
}

.option.wrong {
  background: #f5222d;
  color: white;
  border-color: #f5222d;
}

.option:disabled {
  cursor: not-allowed;
  opacity: 0.8;
}

.actions {
  text-align: center;
  margin: 20px 0;
}

.btn-submit {
  padding: 10px 24px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
}

.btn-submit:hover {
  background: #40a9ff;
}

.result {
  text-align: center;
  margin-top: 20px;
  font-weight: bold;
  font-size: 1.2em;
}
</style>